﻿using Microsoft.AspNetCore.Mvc;
using ZhCun.WebCommon.AL;
using ZhCun.WebCommon.DBModels;

namespace ZhCun.WebCommon.WebApi
{
    //TODO:正常运行后可删除 [ApiController] 
    [LoginAuthorize]
    public class ApiAuthorizeController : ApiController, IAuthorizeController
    {
        TSysLoginToken _LoginToken;

        /// <summary>
        /// 当前登录用户对象,改对象永不为null，访问是如果为null则初始化，且赋值hostaddr
        /// </summary>
        public TSysLoginToken LoginToken
        {
            get
            {
                if (_LoginToken == null)
                {
                    _LoginToken = HttpContext.GetTokenObject();
                    if (_LoginToken == null)
                    {
                        _LoginToken = new TSysLoginToken();
                    }
                    _LoginToken.LoginHost = GetRemoteIp();
                }
                return _LoginToken;
            }
        }

        protected override TAL CreateALObject<TAL>()
        {
            var al = base.CreateALObject<TAL>();
            al.SetLoginState(LoginToken);
            return al;
        }
    }
    /// <summary>
    /// webapi 需要验证的控制器基类(泛型指定AL对象)
    /// </summary>    
    public class ApiAuthorizeController<TAL> : ApiAuthorizeController
        where TAL : BaseAL, new()
    {
        TAL _AL;
        /// <summary>
        /// 当前控制器所依赖的AL对象
        /// </summary>
        public TAL ALObj
        {
            get
            {
                if (_AL == null)
                {
                    _AL = CreateALObject<TAL>();
                }
                return _AL;
            }
        }
    }
}